# -*- coding: UTF-8 -*-
import logging

import conf
import log_helper
from utils import ssh_utils

logger = logging.getLogger('lte')


def __exe_cmd(ssh_client, code):
    for i in range(5):
        res_data = ssh_client.run_cmd("cd /root && ./ampDev " + code)['res']
        if 'success' in res_data:
            res_data = res_data[res_data.index("success"):]
            res_data = res_data.split(':')[1]
            return res_data.strip()
        if i == 4:
            return '-1'


def get_all_power_status():
    if conf.power_debug:
        return ['03', '功放开关:开', '下行功率:01']
    connect_param = {
        'host': conf.REMOTE_HOST,
        'port': 22,
        'username': 'root',
        'pwd': conf.REMOTE_PWD
    }
    ssh_client = ssh_utils.SSHConnection(connect_param)
    result = []
    try:
        ssh_client.connect()
        work_seq = __exe_cmd(ssh_client, 'FF01006C01')
        if work_seq == '-1':
            result.append('timeout')
        else:
            result.append(work_seq)
        res = __exe_cmd(ssh_client, 'FF01040201')
        if res == '00':
            result.append('功放开关：关')
        elif res == '01':
            result.append('功放开关：开')
        else:
            result.append('功放开关：timeout')
        res = __exe_cmd(ssh_client, 'FF01040601')
        if res in ('01', '02', '03', '04', '05'):
            result.append('下行功率：' + str(res))
        # if res == '01':
        #     result.append('下行功率：0.1W')
        # elif res == '02':
        #     result.append('下行功率：1W')
        # elif res == '03':
        #     result.append('下行功率：10W')
        # elif res == '04':
        #     result.append('下行功率：30W')
        # elif res == '05':
        #     result.append('下行功率：60W')
        else:
            result.append('下行功率：timeout')
        return ','.join(result)
    except Exception as e:
        logger.error(log_helper.format_exc_all())
        return '-1'
    finally:
        del ssh_client


def get_band():
    if conf.power_debug:
        return '03'
    connect_param = {
        'host': conf.REMOTE_HOST,
        'port': 22,
        'username': 'root',
        'pwd': conf.REMOTE_PWD
    }
    ssh_client = ssh_utils.SSHConnection(connect_param)
    try:
        ssh_client.connect()
        work_seq = __exe_cmd(ssh_client, 'FF01006C01')
        if work_seq == '-1':
            return '失败'
        else:
            return int(work_seq, 16)
    except Exception as e:
        logger.error(log_helper.format_exc_all())
        return '-1'
    finally:
        del ssh_client


def get_power_status(timeout=None):
    if conf.power_debug:
        return '00'
    connect_param = {
        'host': conf.REMOTE_HOST,
        'port': 22,
        'username': 'root',
        'pwd': conf.REMOTE_PWD
    }
    ssh_client = ssh_utils.SSHConnection(connect_param)
    try:
        ssh_client.connect()
        for i in range(1):
            response = ssh_client.run_cmd("cd /root && ./ampDev FF01FA3001", timeout=timeout)
            if response:
                res_data = response['res']
                if 'success' in res_data:
                    res_data = res_data[res_data.index("success"):]
                    res_data = res_data.split(':')[1]
                    return res_data.strip()
        return '-1'
    except Exception as e:
        logger.error(str(e) + '\n' + log_helper.format_exc_all())
        return '-1'
    finally:
        del ssh_client


def set_power_value(val):
    if conf.power_debug:
        return True
    connect_param = {
        'host': conf.REMOTE_HOST,
        'port': 22,
        'username': 'root',
        'pwd': conf.REMOTE_PWD
    }
    ssh_client = ssh_utils.SSHConnection(connect_param)
    try:
        ssh_client.connect()
        for i in range(5):
            response = ssh_client.run_cmd("cd /root && ./ampDev FF0304060" + str(val))
            if 'success' in response['res']:
                return True
            if i == 4:  # 重试5次后还不成功
                return False
    except Exception as e:
        logger.error(str(e) + '\n' + log_helper.format_exc_all())
        return False
    finally:
        del ssh_client


def shutdown():
    if conf.power_debug:
        return 'success'
    connect_param = {
        'host': conf.REMOTE_HOST,
        'port': 22,
        'username': 'root',
        'pwd': conf.REMOTE_PWD
    }
    ssh_client = ssh_utils.SSHConnection(connect_param)
    try:
        ssh_client.connect()
        rst = __exe_cmd(ssh_client, 'FF03040200')
        logger.info('shutdown power result:' + str(rst))
        return rst
    except Exception as e:
        logger.error(str(e) + '\n' + log_helper.format_exc_all())
        return '-1'
    finally:
        del ssh_client


def startup():
    if conf.power_debug:
        return 'success'
    connect_param = {
        'host': conf.REMOTE_HOST,
        'port': 22,
        'username': 'root',
        'pwd': conf.REMOTE_PWD
    }
    ssh_client = ssh_utils.SSHConnection(connect_param)
    try:
        ssh_client.connect()
        rst = __exe_cmd(ssh_client, 'FF03040201')
        logger.info('shutdown power result:' + str(rst))
        return rst
    except Exception as e:
        logger.error(str(e) + '\n' + log_helper.format_exc_all())
        return '-1'
    finally:
        del ssh_client


def get_power():
    if conf.power_debug:
        return '03'
    connect_param = {
        'host': conf.REMOTE_HOST,
        'port': 22,
        'username': 'root',
        'pwd': conf.REMOTE_PWD
    }
    ssh_client = ssh_utils.SSHConnection(connect_param)
    try:
        ssh_client.connect()
        res = __exe_cmd(ssh_client, 'FF01040601')
        if res in ('01', '02', '03', '04', '05'):
            return int(res)
        return -1
    except Exception as e:
        logger.error(str(e) + '\n' + log_helper.format_exc_all())
        return -1
    finally:
        del ssh_client


if __name__ == '__main__':
    # connect_param = {
    #     'host': '192.168.1.90',
    #     'port': 22,
    #     'username': 'root',
    #     'pwd': 'root123'
    # }
    # ssh_client = ssh_utils.SSHConnection(connect_param)
    # ssh_client.connect()
    # print ssh_client.run_cmd("cd /root && ./ampDev FF01040601")
    # del ssh_client
    print 'success'
